import { createRouter, createWebHistory } from 'vue-router'
import Main from "@/components/Main.vue";
import ParticleLogin from "@/views/auth/ParticleLogin.vue";
import User from "@/views/User.vue";
import Video from "@/views/Video.vue";
import useAuthStore from "@/stores/auth.js";
import Logout from "@/views/Logout.vue";
import {removeToken} from "@/utils/auth.js";
import Index from "@/views/Index.vue";
import Register from "@/views/auth/Register.vue";
import Reset from "@/views/auth/Reset.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'ParticleLogin',
      component: ParticleLogin,
      meta:{
        requiresAuth: false//不需要认证
      }
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
      meta:{
        requiresAuth: false//不需要认证
      }
    },
    {
      path: '/reset',
      name: 'ReSet',
      component: Reset,
      meta:{
        requiresAuth: false//不需要认证
      }
    },
    {
      path: '/main',
      name: 'Main',
      component: Main,
      meta: {
        requiresAuth: true,
      },
      children: [  // 👈 添加子路由配置
        {
          path: 'user',  // 注意这里不需要斜杠开头
          name: 'MainUser',
          component: User
        },
        {
          path: 'video',  // 注意这里不需要斜杠开头
          name: 'MainVideo',
          component: Video
        },
        {
          path: 'logout',
          name: 'Logout',
          component: Logout
        },
        {
          path: 'index',
          name: 'Index',
          component: Index
        }
      ]
    }

  ],
})



// 路由守卫
router.beforeEach(async (to) => {
  const authStore = useAuthStore();
  //已经登录访问登录页直接跳转
  if (authStore.isAuthenticated() && (to.path === '/login' ||to.path === '/register' ||to.path === '/reset')) {
    return '/main/index';
  }
  //需要认证的路径若没有认证，则跳转到登录页
  if(to.meta.requiresAuth){
    const isAuthenticated = authStore.isAuthenticated();
    if(!isAuthenticated){
      return {
        path: '/login',
        query: { redirect: to.fullPath } // 记录原始目标路径
      }
    }

  }
});

export default router;
